package cn.matezk.cloud.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.cloud.beans.*;
import cn.matezk.cloud.beans.tencent.*;
import cn.matezk.cloud.dao.*;
import cn.matezk.cloud.framework.RedisMutexLock;
import cn.matezk.cloud.model.Device;
import cn.matezk.cloud.model.Transfer;
import cn.matezk.cloud.model.UserDevice;
import cn.matezk.cloud.service.IMiniAppService;
import cn.matezk.cloud.service.ITencentService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TencentService implements ITencentService {
    private static final String TENCENT_API = "https://iot.cloud.tencent.com/api/exploreropen/tokenapi";

    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private UserDeviceDao userDeviceDao;
    @Autowired
    private EventDao eventDao;
    @Autowired
    private DeviceStateDao deviceStateDao;
    @Autowired
    private TransferDao transferDao;
    @Autowired
    private FamilyMemberDao familyMemberDao;
    @Autowired
    private IMiniAppService miniAppService;
    @Autowired
    private RedisMutexLock redisMutexLock;

    @Override
    public JSONObject appGetFamilyDeviceList(JSONObject params) throws TencentCloudSDKException {
        int limit = params.getInt("Limit", 50);
        JSONArray array = new JSONArray();
        while (true) {
            JSONObject response = request(params);
            JSONArray deviceList = response.getJSONArray("DeviceList");
            if (ObjectUtil.isNotEmpty(deviceList)) {
                array.addAll(deviceList);
                if (deviceList.size() < limit) {
                    break;
                } else {
                    params.set("Offset", array.size());
                }
            } else {
                break;
            }
        }
        if (ObjectUtil.isNotEmpty(array)) {
            // 所有设备ID
            List<String> deviceIds = array.stream().map(obj -> ((JSONObject) obj).getStr("DeviceId")).collect(Collectors.toList());
            // 查询设备快捷键和在线状态
            List<DeviceExt> exts = deviceDao.batchQueryDeviceExt(deviceIds);
            Map<String, DeviceExt> extMap = exts.stream().collect(Collectors.toMap(DeviceExt::getDeviceId, DeviceExt::self));
            // 遍历设备
            array.forEach(dev -> {
                JSONObject item = (JSONObject) dev;
                item.set("IsShare", false);
                String deviceId = item.getStr("DeviceId");
                if (extMap.containsKey(deviceId)) {
                    DeviceExt ext = extMap.get(deviceId);
                    item.set("Switch1", ext.getSwitch1());
                    item.set("DetectState1", ext.getDetectState1());
                    item.set("Amount", BigDecimal.valueOf(ext.getAmount() / 100.0));
                    item.set("ExpireDate", DateUtil.format(ext.getExpireDate(), DatePattern.NORM_DATE_PATTERN));
                    item.set("Reported", ext.getReported());
                }
            });
        }
        return JSONUtil.createObj()
                .set("Total", array.size())
                .set("DeviceList", array);
    }

    @Override
    public JSONObject appListUserShareDevices(JSONObject params) throws TencentCloudSDKException {
        // 所有设备集合
        List<ShareDevice> deviceList = new ArrayList<>();
        int limit = params.getInt("Limit", 100);
        JSONArray array = new JSONArray();
        while (true) {
            JSONObject response = request(params);
            JSONArray devices = response.getJSONArray("ShareDevices");
            if (ObjectUtil.isNotEmpty(devices)) {
                array.addAll(devices);
                if (devices.size() < limit) {
                    break;
                } else {
                    params.set("Offset", array.size());
                }
            } else {
                break;
            }
        }
        if (ObjectUtil.isNotEmpty(array)) {
            // 云端设备
            List<ShareDevice> cloudList = JSONUtil.toList(array, ShareDevice.class);
            cloudList.forEach(dev -> dev.setIsLocal(Boolean.FALSE));
            deviceList.addAll(cloudList);
        }
        // 查询本地设备
        List<ShareDevice> localList = userDeviceDao.shareDevice(params.getJSONObject("ext").getStr("userId"));
        localList.forEach(dev -> dev.setIsLocal(Boolean.TRUE));
        if (ObjectUtil.isNotEmpty(localList)) {
            deviceList.addAll(localList);
        }
        if (ObjectUtil.isNotEmpty(deviceList)) {
            // 所有设备ID
            List<String> deviceIds = deviceList.stream().map(ShareDevice::getDeviceId).collect(Collectors.toList());
            // 查询设备快捷键和在线状态
            List<DeviceExt> exts = deviceDao.batchQueryDeviceExt(deviceIds);
            Map<String, DeviceExt> extMap = exts.stream().collect(Collectors.toMap(DeviceExt::getDeviceId, DeviceExt::self));
            // 遍历设备
            deviceList.forEach(dev -> {
                if (extMap.containsKey(dev.getDeviceId())) {
                    DeviceExt ext = extMap.get(dev.getDeviceId());
                    dev.setOnline(ext.getOnline());
                    dev.setSwitch1(ext.getSwitch1());
                    dev.setDetectState1(ext.getDetectState1());
                    dev.setAmount(BigDecimal.valueOf(ext.getAmount() / 100.0));
                    dev.setReported(ext.getReported());
                }
            });
        }
        return JSONUtil.createObj()
                .set("Total", deviceList.size())
                .set("ShareDevices", deviceList);
    }

    @Override
    @Transactional
    public JSONObject appDeleteDeviceInFamily(JSONObject params) throws TencentCloudSDKException {
        String deviceId = params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName"));
        // 先删除本地数据库
        deviceDao.unbind(deviceId);
        userDeviceDao.unbindByDeviceId(deviceId);
        eventDao.deleteByDeviceId(deviceId);
        deviceStateDao.deleteByDeviceId(deviceId);
        params.remove("ext");
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appBindUserShareDevice(JSONObject params) throws TencentCloudSDKException {
        String deviceId = params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName"));
        JSONObject ext = params.getJSONObject("ext");
        params.remove(ext);
        // 要修改的数据
        UserDevice ud = new UserDevice();
        ud.setDeviceId(deviceId);
        ud.setUserId(ext.getStr("SharedId"));
        ud.setRole(UserDevice.ROLE_SHARE);
        ud.setNickName(ext.getStr("SharedNick"));
        ud.setBindTime(Calendar.getInstance().getTimeInMillis() / 1000);
        ud.setProductIcon(ext.getStr("IconUrl"));
        try {
            JSONObject response = request(params);
            // 先解绑
            userDeviceDao.unbind(deviceId, ext.getStr("SharedId"));
            // 再绑定
            userDeviceDao.bind(ud);
            return response;
        } catch (TencentCloudSDKException e) {
            if ("InvalidParameterValue.UserBindExceedLimit".equals(e.getErrorCode()) || "InvalidParameterValue.DeviceShareExceedLimit".equals(e.getErrorCode())) {
                // 先解绑
                userDeviceDao.unbind(deviceId, ext.getStr("SharedId"));
                ud.setIsLocal(Boolean.TRUE);
                // 再绑定
                userDeviceDao.bind(ud);
                return JSONUtil.createObj().set("Response", JSONUtil.createObj().set("RequestId", IdUtil.fastSimpleUUID()));
            } else {
                throw e;
            }
        }
    }

    @Override
    @Transactional
    public JSONObject appRemoveShareDeviceUser(JSONObject params) {
        String deviceId = params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName"));
        userDeviceDao.unbind(deviceId, params.getStr("RemoveUserId", params.getJSONObject("ext").getStr("RemoveUserId")));
        params.remove("ext");
        try {
            return request(params);
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage());
            return JSONUtil.createObj();
        }
    }

    @Override
    public JSONObject appRemoveUserShareDevice(JSONObject params) {
        String deviceId = params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName"));
        String removeUserId = params.getJSONObject("ext").getStr("RemoveUserId");
        userDeviceDao.unbind(deviceId, removeUserId);
        params.remove("ext");
        try {
            return request(params);
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage());
            return JSONUtil.createObj();
        }
    }

    @Override
    public JSONObject appListShareDeviceUsers(JSONObject params) throws TencentCloudSDKException {
        JSONObject object = request(params);
        int total = object.getInt("Total");
        if (total == 0) return object;
        // 查询设备所有的分享用户
        String deviceId = params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName"));
        List<UserDevice> uds = userDeviceDao.matchRole(deviceId, UserDevice.ROLE_SHARE);
        Map<String, UserDevice> uMap = new HashMap<>();
        for (UserDevice ud : uds)
            uMap.put(ud.getUserId(), ud);
        JSONArray users = object.getJSONArray("Users");
        for (int i = 0; i < users.size(); i++) {
            JSONObject user = users.getJSONObject(i);
            String userId = user.getStr("UserID");
            if (!uMap.containsKey(userId)) {
                // 新增
                UserDevice add = new UserDevice();
                add.setDeviceId(deviceId);
                add.setUserId(userId);
                add.setNickName(user.getStr("NickName"));
                add.setBindTime(user.getLong("BindTime"));
                add.setRole(UserDevice.ROLE_SHARE);
                userDeviceDao.bind(add);
                continue;
            }
            UserDevice ud = uMap.get(userId);
            if (ObjectUtil.isNotEmpty(ud.getNickName()))
                user.set("NickName", ud.getNickName());
            uMap.remove(userId);
        }
        if (uMap.isEmpty()) return object;
        for (String userId : uMap.keySet()) {
            UserDevice ud = uMap.get(userId);
            if (ObjectUtil.isNull(ud.getBindTime())) continue;
            total += 1;
            JSONObject user = JSONUtil.createObj()
                    .set("Avatar", "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132")
                    .set("BindTime", ud.getBindTime())
                    .set("NickName", ObjectUtil.isEmpty(ud.getNickName()) ? "微信用户" : ud.getNickName())
                    .set("UserID", ud.getUserId());
            users.add(user);
            object.set("Total", total);
        }
        return object;
    }

    @Override
    @Transactional
    public JSONObject appJoinFamily(JSONObject params) throws TencentCloudSDKException {
        // 删除家庭成员
        JSONObject ext = params.getJSONObject("ext");
        familyMemberDao.bind(ext.getStr("FamilyId"), ext.getStr("MemberId"));
        params.remove("ext");
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appExitFamily(JSONObject params) throws TencentCloudSDKException {
        // 删除家庭成员
        JSONObject ext = params.getJSONObject("ext");
        familyMemberDao.unbind(params.getStr("FamilyId"), ext.getStr("UserId"));
        params.remove("ext");
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appDeleteFamilyMember(JSONObject params) throws TencentCloudSDKException {
        // 删除家庭成员
        familyMemberDao.unbind(params.getStr("FamilyId"), params.getStr("MemberId"));
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appTransferFamily(JSONObject params) throws TencentCloudSDKException {
        // 移交家庭
        userDeviceDao.changeFamilyDeviceOwner(params.getStr("FamilyId"), params.getJSONObject("ext").getStr("FromUserId"), params.getStr("ToUserID"));
        // TODO 删除新家庭管理员的分享设备 腾讯未删除
        // userDeviceDao.unbindByFamilyMember(params.getStr("FamilyId"), params.getStr("ToUserID"));
        // 删除原有家庭成员
        familyMemberDao.unbind(params.getStr("FamilyId"), params.getStr("ToUserID"));
        // 原有家庭管理员变为成员
        familyMemberDao.bind(params.getStr("FamilyId"), params.getJSONObject("ext").getStr("FromUserId"));
        params.remove("ext");
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appUpdateDeviceInFamily(JSONObject params) throws TencentCloudSDKException {
        Device device = new Device();
        device.setDeviceId(params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName")));
        device.setAliasName(params.getStr("AliasName"));
        deviceDao.updateByPrimaryKeySelective(device);
        return request(params);
    }

    @Override
    @Transactional
    public JSONObject appModifyFamilyDeviceRoom(JSONObject params) throws TencentCloudSDKException {
        Device device = new Device();
        device.setDeviceId(params.getStr("ProductId").concat("/").concat(params.getStr("DeviceName")));
        device.setFamilyId(params.getStr("FamilyId"));
        device.setRoomId(params.getStr("RoomId"));
        deviceDao.updateByPrimaryKeySelective(device);
        return request(params);
    }

    @Override
    public String sceneTransfer(CreateTransfer sceneTransfer) throws TencentCloudSDKException {
        Transfer transfer = new Transfer();
        transfer.setId(IdUtil.fastSimpleUUID());
        transfer.setFrom(sceneTransfer.getUserId());
        transfer.setFromAccessToken(sceneTransfer.getAccessToken());
        // 自动场景
        List<String> deviceIds = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(sceneTransfer.getAuto())) {
            List<Automation> automation = new ArrayList<>();
            for (String sceneId : sceneTransfer.getAuto()) {
                JSONObject params = JSONUtil.createObj();
                params.set("AccessToken", sceneTransfer.getAccessToken());
                params.set("Action", "AppDescribeAutomation");
                params.set("AutomationId", sceneId);
                params.set("RegionId", 1);
                String requestId = IdUtil.fastSimpleUUID();
                params.set("RequestId", requestId);
                HttpResponse response = new HttpRequest(TENCENT_API).method(Method.POST).body(params.toString()).execute();
                if (response.isOk()) {
                    log.info(response.body());
                    AutomationResponse detail = JSONUtil.toBean(response.body(), AutomationResponse.class);
                    ;
                    automation.add(detail.getData().getData());
                    for (Condition condition : detail.getData().getData().getConditions()) {
                        if (condition.getCondType() == 0) {
                            String deviceId = condition.getProperty().getProductId().concat("/").concat(condition.getProperty().getDeviceName());
                            if (!deviceIds.contains(deviceId)) {
                                deviceIds.add(deviceId);
                            }
                        }
                    }
                    for (Action action : detail.getData().getData().getActions()) {
                        if (action.getActionType().intValue() == 0) {
                            String deviceId = action.getProductId().concat("/").concat(action.getDeviceName());
                            if (!deviceIds.contains(deviceId)) {
                                deviceIds.add(deviceId);
                            }
                        } else if (action.getActionType().intValue() == 2) {
                            sceneTransfer.addManual(action.getData());
                        }
                    }
                } else {
                    throw new TencentCloudSDKException(String.format("接口错误(%d)", response.getStatus()), requestId, String.valueOf(response.getStatus()));
                }
            }
            transfer.setAutomation(automation);
        }
        // 手动场景
        if (ObjectUtil.isNotEmpty(sceneTransfer.getManual())) {
            List<Manual> manual = new ArrayList<>();
            int offset = 0;
            while (true) {
                JSONObject params = JSONUtil.createObj();
                params.set("AccessToken", sceneTransfer.getAccessToken());
                params.set("Action", "AppGetSceneList");
                params.set("FamilyId", sceneTransfer.getFamilyId());
                params.set("Offset", offset);
                params.set("Limit", 50);
                params.set("RegionId", 1);
                String requestId = IdUtil.fastSimpleUUID();
                params.set("RequestId", requestId);
                HttpResponse response = new HttpRequest(TENCENT_API).method(Method.POST).body(params.toString()).execute();
                if (response.isOk()) {
                    ManualResponse manualResponse = JSONUtil.toBean(response.body(), ManualResponse.class);
                    if (ObjectUtil.isEmpty(manualResponse.getData().getSceneList())) break;
                    for (Manual m : manualResponse.getData().getSceneList()) {
                        if (!sceneTransfer.getManual().contains(m.getSceneId())) continue;
                        manual.add(m);
                        for (Action action : m.getActions()) {
                            if (action.getActionType().intValue() != 0) continue;
                            String deviceId = action.getProductId().concat("/").concat(action.getDeviceName());
                            if (!deviceIds.contains(deviceId)) {
                                deviceIds.add(deviceId);
                            }
                        }
                    }
                    if (manualResponse.getData().getSceneList().size() < 50) break;
                    offset += 50;
                } else {
                    throw new TencentCloudSDKException(String.format("接口错误(%d)", response.getStatus()), requestId, String.valueOf(response.getStatus()));
                }
            }
            transfer.setManual(manual);
        }
        // 查询设备定时任务
        if (ObjectUtil.isNotEmpty(deviceIds)) {
            List<DeviceTimer> timer = new ArrayList<>();
            for (String deviceId : deviceIds) {
                int offset = 0;
                while (true) {
                    JSONObject params = JSONUtil.createObj();
                    params.set("AccessToken", sceneTransfer.getAccessToken());
                    params.set("Action", "AppGetTimerList");
                    params.set("ProductId", deviceId.split("/")[0]);
                    params.set("DeviceName", deviceId.split("/")[1]);
                    params.set("Offset", offset);
                    params.set("Limit", 50);
                    params.set("RegionId", 1);
                    String requestId = IdUtil.fastSimpleUUID();
                    params.set("RequestId", requestId);
                    HttpResponse response = new HttpRequest(TENCENT_API).method(Method.POST).body(params.toString()).execute();
                    if (response.isOk()) {
                        TimerResponse timerResponse = JSONUtil.toBean(response.body(), TimerResponse.class);
                        if (ObjectUtil.isEmpty(timerResponse.getData().getTimerList())) break;
                        for (DeviceTimer t : timerResponse.getData().getTimerList()) {
                            timer.add(t);
                        }
                        if (timerResponse.getData().getTimerList().size() < 50) break;
                        offset += 50;
                    } else {
                        throw new TencentCloudSDKException(String.format("接口错误(%d)", response.getStatus()), requestId, String.valueOf(response.getStatus()));
                    }
                }
            }
            transfer.setTimer(timer);
        }
        // 获取用户设备列表
        List<cn.matezk.cloud.beans.tencent.Device> device = new ArrayList<>();
        int offset = 0;
        while (true) {
            String requestId = IdUtil.fastSimpleUUID();
            JSONObject params = JSONUtil.createObj()
                    .set("AccessToken", sceneTransfer.getAccessToken())
                    .set("Action", "AppGetFamilyDeviceList")
                    .set("FamilyId", sceneTransfer.getFamilyId())
                    .set("Offset", offset)
                    .set("Limit", 50)
                    .set("RegionId", 1)
                    .set("RequestId", requestId);
            HttpResponse response = new HttpRequest(TENCENT_API).method(Method.POST).body(params.toString()).execute();
            if (response.isOk()) {
                DeviceResponse deviceResponse = JSONUtil.toBean(response.body(), DeviceResponse.class);
                if (ObjectUtil.isEmpty(deviceResponse.getData().getDeviceList())) break;
                for (cn.matezk.cloud.beans.tencent.Device d : deviceResponse.getData().getDeviceList()) {
                    if (deviceIds.contains(d.getDeviceId())) {
                        device.add(d);
                    }
                }
                if (deviceResponse.getData().getDeviceList().size() < 50) break;
                offset += 50;
            } else {
                throw new TencentCloudSDKException(String.format("接口错误(%d)", response.getStatus()), requestId, String.valueOf(response.getStatus()));
            }
        }
        transfer.setDevice(device);
        transferDao.insertSelective(transfer);
        return transfer.getId();
    }

    @Override
    public void agreeTransfer(AgreeTransfer agreeTransfer) throws TencentCloudSDKException, InterruptedException {
        String lockKey = "transfer.".concat(agreeTransfer.getTransferId());
        if (redisMutexLock.tryLock(lockKey, 1)) {
            try {
                Transfer transfer = transferDao.selectByPrimaryKey(agreeTransfer.getTransferId());
                if (ObjectUtil.isEmpty(transfer) || transfer.getStatus().intValue() != 0 || transfer.expire()) {
                    throw new InternalException("链接已失效");
                }
                transfer.setTo(agreeTransfer.getUserId());
                transfer.setAgreeTime(new Date());
                try {
                    // 删除原来的设备
                    for (cn.matezk.cloud.beans.tencent.Device d : transfer.getDevice()) {
                        JSONObject params = JSONUtil.createObj()
                                .set("AccessToken", transfer.getFromAccessToken())
                                .set("Action", "AppDeleteDeviceInFamily")
                                .set("FamilyId", d.getFamilyId())
                                .set("RoomId", d.getRoomId())
                                .set("ProductId", d.getProductId())
                                .set("DeviceName", d.getDeviceName());
                        appDeleteDeviceInFamily(params);
                    }
                    // 绑定到新用户
                    for (cn.matezk.cloud.beans.tencent.Device d : transfer.getDevice()) {
                        BindDeviceRequest bind = new BindDeviceRequest();
                        bind.setAccessToken(agreeTransfer.getAccessToken());
                        bind.setProductId(d.getProductId());
                        bind.setDeviceName(d.getDeviceName());
                        bind.setFamilyId(agreeTransfer.getFamilyId());
                        bind.setRoomId(agreeTransfer.getRoomId());
                        bind.setUserId(agreeTransfer.getUserId());
                        miniAppService.bindFamily(bind);
                    }
                    // 创建定时任务
                    for (DeviceTimer timer : transfer.getTimer()) {
                        JSONObject params = JSONUtil.createObj()
                                .set("AccessToken", agreeTransfer.getAccessToken())
                                .set("Action", "AppCreateTimer")
                                .set("ProductId", timer.getProductId())
                                .set("DeviceName", timer.getDeviceName())
                                .set("TimerName", timer.getTimerName())
                                .set("Days", timer.getDays())
                                .set("TimePoint", timer.getTimePoint())
                                .set("Repeat", timer.getRepeat())
                                .set("Data", timer.getData());
                        request(params);
                    }
                    // 手动场景
                    for (Manual manual : transfer.getManual()) {
                        // 删除手动场景
                        JSONObject params = JSONUtil.createObj()
                                .set("AccessToken", transfer.getFromAccessToken())
                                .set("Action", "AppDeleteScene")
                                .set("SceneId", manual.getSceneId());
                        request(params);
                        // 创建手动场景
                        params.clear();
                        params.set("AccessToken", agreeTransfer.getAccessToken())
                                .set("Action", "AppCreateScene")
                                .set("FamilyId", agreeTransfer.getFamilyId())
                                .set("SceneName", manual.getSceneName())
                                .set("SceneIcon", manual.getSceneIcon())
                                .set("Actions", manual.getActions());
                        request(params);
                    }
                    // 自动场景
                    for (Automation automation : transfer.getAutomation()) {
                        // 删除自动场景
                        JSONObject params = JSONUtil.createObj()
                                .set("AccessToken", transfer.getFromAccessToken())
                                .set("Action", "AppDeleteAutomation")
                                .set("AutomationId", automation.getAutomationId());
                        request(params);
                        // 创建自动场景
                        params.clear();
                        params.set("AccessToken", agreeTransfer.getAccessToken())
                                .set("Action", "AppCreateAutomation")
                                .set("FamilyId", agreeTransfer.getFamilyId())
                                .set("Icon", automation.getIcon())
                                .set("Name", automation.getName())
                                .set("Status", automation.getStatus())
                                .set("MatchType", automation.getMatchType())
                                .set("Conditions", automation.getConditions())
                                .set("Actions", automation.getActions())
                                .set("EffectiveBeginTime", automation.getEffectiveBeginTime())
                                .set("EffectiveEndTime", automation.getEffectiveEndTime())
                                .set("EffectiveDays", automation.getEffectiveDays());
                        request(params);
                        transfer.setStatus(1);
                    }
                } catch (Exception e) {
                    transfer.setStatus(2);
                    throw e;
                } finally {
                    transferDao.updateByPrimaryKeySelective(transfer);
                }
            } finally {
                redisMutexLock.unlock(lockKey);
            }
        }
    }

    @Override
    public JSONObject request(JSONObject params) throws TencentCloudSDKException {
        params.set("RegionId", 1);
        String requestId = IdUtil.fastSimpleUUID();
        params.set("RequestId", requestId);
        HttpResponse response = new HttpRequest(TENCENT_API).method(Method.POST).body(params.toString()).execute();
        try {
            if (response.isOk()) {
                JSONObject payload = JSONUtil.parseObj(response.body());
                if (0 != payload.getInt("code")) {
                    JSONObject error = payload.getJSONObject("data").getJSONObject("Error");
                    throw new TencentCloudSDKException(error.getStr("Message"), requestId, error.getStr("Code"));
                }
                return payload.getJSONObject("data");
            } else {
                throw new TencentCloudSDKException(String.format("接口错误(%d)", response.getStatus()), requestId, String.valueOf(response.getStatus()));
            }
        } finally {
            response.close();
        }
    }
}
